package com.review.Test.Master_Worker;

import java.util.HashMap;
import java.util.Map.Entry;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentLinkedQueue;

public class Master {

	ConcurrentLinkedQueue<Task> tasks = new ConcurrentLinkedQueue<>();

	HashMap<String, Thread> workers = new HashMap<>();

	ConcurrentHashMap<String, Object> result = new ConcurrentHashMap<>();

	public Master(Worker worker, int num){
		worker.setTasks(this.tasks);
		worker.setResult(this.result);

		for (int i = 1; i <= num; i++) {
			workers.put("worker"+i, new Thread(worker));
		}
	}

	public void submit(Task task){
		this.tasks.add(task);
	}

	public void exexute(){
		for (Entry<String, Thread> worker : workers.entrySet()) {
			worker.getValue().start();
		}
	}

	public boolean isComplete(){
		for (Entry<String, Thread> worker : workers.entrySet()) {
			if (worker.getValue().getState() != Thread.State.TERMINATED) {
				return false;
			}
		}
		return true;
	}
	
	public int summary(){
		int sum = 0;
		for (Entry<String, Object> r : result.entrySet()) {
			sum += (Integer)r.getValue();
		}
		
		return sum;
	}

}
